package com.wash.shoes.helper;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.wash.shoes.common.enums.FactoryStatusEnum;
import com.wash.shoes.entity.FactoryAreaConfigPo;
import com.wash.shoes.entity.FactoryPo;
import com.wash.shoes.exception.WashException;
import com.wash.shoes.service.FactoryAreaConfigService;
import com.wash.shoes.service.FactoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 工厂辅助类,通过用户的省市区地址 匹配返回对应工厂的
 */
@Component
@RequiredArgsConstructor
public class FactoryAddressHelper {

    private final FactoryService factoryService;
    private final FactoryAreaConfigService factoryAreaConfigService;

    /**
     * 根据店铺的省市区获取对应店铺范围内配置的工厂的地址为收货地址
     *
     * @param city      市
     * @param provinces 省
     * @param country   区/县
     * @return
     */
    public FactoryPo getFactoryAddressWithShopAddress(String provinces, String city, String country, String brandId) {
        if (StringUtils.isNotEmpty(provinces)) {
            provinces = provinces.replace("省", "").replace("市", "").replace("区", "");
        }
        // 查询工厂区域配置,优先查省市配置，没有则查省市配置
        // 先查省市配置
        FactoryAreaConfigPo factoryAreaConfigPo = factoryAreaConfigService.getOne(
                new LambdaQueryWrapper<FactoryAreaConfigPo>()
                        .likeRight(FactoryAreaConfigPo::getProvinces, provinces)
                        .eq(FactoryAreaConfigPo::getCity, city)
                        .eq(FactoryAreaConfigPo::getStatus, 1)
                        .eq(Objects.nonNull(brandId), FactoryAreaConfigPo::getBrandId, brandId)
                        .last("limit 1")
        );
        // 如果没有，再查省配置
        if (Objects.isNull(factoryAreaConfigPo)) {
            factoryAreaConfigPo = factoryAreaConfigService.getOne(
                    new LambdaQueryWrapper<FactoryAreaConfigPo>()
                            .likeRight(FactoryAreaConfigPo::getProvinces, provinces)
                            .eq(FactoryAreaConfigPo::getStatus, 1)
                            .eq(Objects.nonNull(brandId), FactoryAreaConfigPo::getBrandId, brandId)
                            .last("limit 1")
            );
        }
        if (factoryAreaConfigPo == null || factoryAreaConfigPo.getFactoryId() == null) {
            throw new WashException("未找到工厂配置信息");
        }
        FactoryPo factoryPo = factoryService
                .getOne(new LambdaQueryWrapper<FactoryPo>().eq(FactoryPo::getId, factoryAreaConfigPo.getFactoryId())
                        .eq(FactoryPo::getStatus, FactoryStatusEnum.NORMAL));
        Assert.notNull(factoryPo, "未找到工厂信息,FactoryId:" + factoryAreaConfigPo.getFactoryId());
        return factoryPo;
    }
}
